package com.linln.admin.store.controller;

import com.linln.admin.store.validator.BaseinfoValid;
import com.linln.common.enums.StatusEnum;
import com.linln.common.utils.EntityBeanUtil;
import com.linln.common.utils.ResultVoUtil;
import com.linln.common.utils.StatusUtil;
import com.linln.common.vo.ResultVo;
import com.linln.modules.ad.domain.AdInfo;
import com.linln.modules.message.domain.MessageType;
import com.linln.modules.store.domain.Storeinfo;
import com.linln.modules.store.domain.Type;
import com.linln.modules.store.service.StoreinfoService;
import com.linln.modules.store.service.TypeService;
import com.linln.modules.system.domain.Area;
import com.linln.modules.system.domain.Dept;
import com.linln.modules.system.service.AreaService;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @author hct
 * @date 2019/09/12
 */
@Controller
@RequestMapping("/store/baseinfo")
public class BaseinfoController {

    @Autowired
    private StoreinfoService baseinfoService;
    @Autowired
    private TypeService typeService;
    @Autowired
    private AreaService areaService;

    /**
     * 列表页面
     */
    @GetMapping("/index")
    @RequiresPermissions("store:baseinfo:index")
    public String index(Model model, Storeinfo baseinfo,Long typeId) {

    	
    	ExampleMatcher matchertype = ExampleMatcher.matching();
        // 获取部门列表
    	Type type=new Type();
        Example<Type> exampleType = Example.of(type, matchertype);
        Sort sort = new Sort(Sort.Direction.ASC, "num");
        List<Type> typelist = typeService.getListByExample(exampleType, sort);
		/*List<Type> typelist=new ArrayList<Type>();
        for(Type messageType:typealllist) {
        	if(messageType.getPid()!=null && messageType.getPid().longValue()>0) {
        		typelist.add(messageType);
        	}
        }*/
    	
    	
    	
        // 创建匹配器，进行动态查询匹配
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withMatcher("store_name", match -> match.contains());
        if(typeId!=null && typeId.longValue()>0) {
        	Type typenew=new Type();
        	typenew.setId(typeId);
        	baseinfo.setStoretype(typenew); 
        }
        // 获取数据列表
        Example<Storeinfo> example = Example.of(baseinfo, matcher);
        Page<Storeinfo> list = baseinfoService.getPageList(example);
        /*for(Storeinfo adinfo:list.getContent()) {
        	if(adinfo==null) continue;
        	Area area=areaService.findByCode(adinfo.getArea());
        	if(area!=null) {
        		adinfo.setAreaname(area.getName());
        	}
        }*/
        for (Storeinfo storeInfo_ :list.getContent()
                ) {
                    if(storeInfo_==null) continue;
                    Area area = areaService.findByCode(storeInfo_.getArea());
                    if(area != null){
                        Area parea = areaService.getById(area.getPid());
                        storeInfo_.setAreaname(area.getName());
                        if(parea != null){
                        	storeInfo_.setAreaname(parea.getName()+area.getName());
                        }
                    }
                }
        // 封装数据
        model.addAttribute("typelist", typelist);
        model.addAttribute("typeId", typeId);
        model.addAttribute("list", list.getContent());
        model.addAttribute("page", list);
        return "/store/baseinfo/index";
    }

    /**
     * 跳转到添加页面
     */
    @GetMapping("/add")
    @RequiresPermissions("store:baseinfo:add")
    public String toAdd(Type type) {
    	
    	// 创建匹配器，进行动态查询匹配
        ExampleMatcher matcher = ExampleMatcher.matching().
                withMatcher("title", match -> match.contains());

        // 获取部门列表
        Example<Type> example = Example.of(type, matcher);
        Sort sort = new Sort(Sort.Direction.ASC, "num");
    	List<Type> typeList=typeService.getListByExample( example, sort);
        return "/store/baseinfo/add";
    }

    /**
     * 跳转到编辑页面
     */
    @GetMapping("/edit/{id}")
    @RequiresPermissions("store:baseinfo:edit")
    public String toEdit(@PathVariable("id") Storeinfo baseinfo, Model model) {
        model.addAttribute("baseinfo", baseinfo);
        return "/store/baseinfo/add";
    }

    /**
     * 保存添加/修改的数据
     * @param valid 验证对象
     */
    @PostMapping("/save")
    @RequiresPermissions({"store:baseinfo:add", "store:baseinfo:edit"})
    @ResponseBody
    public ResultVo save(@Validated BaseinfoValid valid, Storeinfo baseinfo) {
        // 复制保留无需修改的数据
        if (baseinfo.getId() != null) {
            Storeinfo beBaseinfo = baseinfoService.getById(baseinfo.getId());
            EntityBeanUtil.copyProperties(beBaseinfo, baseinfo);
        }

        // 保存数据
        baseinfoService.save(baseinfo);
        return ResultVoUtil.SAVE_SUCCESS;
    }

    /**
     * 跳转到详细页面
     */
    @GetMapping("/detail/{id}")
    @RequiresPermissions("store:baseinfo:detail")
    public String toDetail(@PathVariable("id") Storeinfo baseinfo, Model model) {
    	
    	Area area=areaService.findByCode(baseinfo.getArea());
    	if(area!=null) {
    		baseinfo.setAreaname(area.getName());
    	}
        model.addAttribute("baseinfo",baseinfo);
        return "/store/baseinfo/detail";
    }

    /**
     * 设置一条或者多条数据的状态
     */
    @RequestMapping("/status/{param}")
    @RequiresPermissions("store:baseinfo:status")
    @ResponseBody
    public ResultVo status(
            @PathVariable("param") String param,
            @RequestParam(value = "ids", required = false) List<Long> ids) {
        // 更新状态
        StatusEnum statusEnum = StatusUtil.getStatusEnum(param);
        if (baseinfoService.updateStatus(statusEnum, ids)) {
            return ResultVoUtil.success(statusEnum.getMessage() + "成功");
        } else {
            return ResultVoUtil.error(statusEnum.getMessage() + "失败，请重新操作");
        }
    }
}